package hlhj.fhp.burst.activitys

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.Color
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.widget.*
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.google.gson.Gson
import com.liaoinstan.springview.container.DefaultFooter
import com.liaoinstan.springview.container.DefaultHeader
import com.liaoinstan.springview.widget.SpringView
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.lzy.okgo.request.base.Request
import com.tenma.ventures.base.TMActivity
import com.tenma.ventures.bean.TMUser
import com.tenma.ventures.bean.utils.TMEnterUtil
import com.tenma.ventures.bean.utils.TMSharedPUtil
import com.tenma.ventures.config.TMServerConfig
import com.tenma.ventures.share.bean.TMLinkShare
import com.tenma.ventures.share.util.TMShareUtil
import hlhj.fhp.burst.*
import hlhj.fhp.burst.adapter.CommentAdp
import hlhj.fhp.burst.adapter.Vpadp
import hlhj.fhp.burst.bean.BaseBean
import hlhj.fhp.burst.bean.BurstListBean
import hlhj.fhp.burst.camera.util.LogUtil
import hlhj.fhp.burst.customView.LoadingDialog
import hlhj.fhp.burst.ninegrid.ImageInfo
import hlhj.fhp.burst.ninegrid.NineGridView
import hlhj.fhp.burst.ninegrid.preview.NineGridViewClickAdapter
import kotlinx.android.synthetic.main.activity_burst_aty.*
import kotlinx.android.synthetic.main.burst_head_pager.view.*
import java.util.ArrayList

class BurstAty : TMActivity(), SpringView.OnFreshListener {
    private var page=1;
    private lateinit var loadDialog:LoadingDialog
    private lateinit var pagerAdp:Vpadp
    private val pagerDatas=ArrayList<BurstListBean.DataBean.BannerBean>()
    private lateinit var adp :BaseQuickAdapter<BurstListBean.DataBean.ListBean,BaseViewHolder>
    private val datas=ArrayList<BurstListBean.DataBean.ListBean>()
    private lateinit var headview:View
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_burst_aty)
        NineGridView.setImageLoader(object :NineGridView.ImageLoader{
            override fun onDisplayImage(context: Context?, imageView: ImageView?, url: String?) {
                Glide.with(context!!).load(url).apply(GlideUtil.loadImageOption()).into(imageView!!)
            }

            override fun getCacheImage(url: String?): Bitmap? {
                return null
            }
        })
        Contents.PUBLICK_URL=TMServerConfig.BASE_URL
        if (ContextCompat.checkSelfPermission(this,Manifest.permission.READ_PHONE_STATE)!=PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED
                ||ContextCompat.checkSelfPermission(this,Manifest.permission.CAMERA)!=PackageManager.PERMISSION_GRANTED
                ||ContextCompat.checkSelfPermission(this,Manifest.permission.RECORD_AUDIO)!=PackageManager.PERMISSION_GRANTED
                )run{
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_PHONE_STATE,Manifest.permission.WRITE_EXTERNAL_STORAGE
            ,Manifest.permission.CAMERA,Manifest.permission.RECORD_AUDIO),0)
        }
        if (null!=TMSharedPUtil.getTMThemeColor(this)&&TMSharedPUtil.getTMThemeColor(this).length>0){
            loTittle.setBackgroundColor(Color.parseColor(TMSharedPUtil.getTMThemeColor(this)))
        }
        loadDialog= LoadingDialog(this)
        initView()
        initData()


        btExit.setOnClickListener {
            finish()
        }

    }

    private fun initData() {
        OkGo.get<String>(Contents.PUBLICK_URL+Contents.LIST)
                .params("page",page)
                .execute(object :StringCallback(){
                    override fun onStart(request: Request<String, out Request<Any, Request<*, *>>>?) {
                        super.onStart(request)
                        loadDialog.show()
                    }
                    override fun onSuccess(response: Response<String>?) {
                        loadDialog.dismiss()
                        spView.onFinishFreshAndLoad()
                        val body = response?.body()
                        val bean = Gson().fromJson(body, BurstListBean::class.java)
                        if (bean?.code==1){
                            datas.addAll(bean?.data.list)
                            if (pagerDatas.size==0){
                                pagerDatas.addAll(bean?.data.banner)
                                pagerAdp= Vpadp(this@BurstAty,pagerDatas)
                            }
                            adp.notifyDataSetChanged()
                        }
                    }
                })
    }

    private fun initView() {
        initSp()
        /*头布局*/
        headview = LayoutInflater.from(this).inflate(R.layout.burst_head_pager, null)
        headview.btGoBurst.text="我要\n爆料"
        headview.btGoBurst.setOnClickListener {
            val intent = Intent(this@BurstAty, MyBurstAty::class.java)
            startActivity(intent)
        }
        adp=object :BaseQuickAdapter<BurstListBean.DataBean.ListBean,BaseViewHolder>(R.layout.burst_item,datas){
            override fun convert(helper: BaseViewHolder?, item: BurstListBean.DataBean.ListBean?) {
                LogUtil.e("info",Contents.PUBLICK_URL+item?.iconName?.replace("\\","/"))

                Glide.with(mContext)
                        .load(Contents.PUBLICK_URL+item?.iconName?.replace("\\","/"))
                        .apply(GlideUtil.loadHeadOption())
                        .into(helper?.getView(R.id.userIcon)!!)
//                helper?.setText(R.id.userName,item?.nickName)
                helper?.setText(R.id.btZan,item?.laud_num.toString())
                helper?.setText(R.id.tvHowLong,TimeUtils.convertTimeToFormat(item?.create_at?.toLong()!!))
                val nineGridView = helper?.getView<NineGridView>(R.id.nineGrideView)
                val btCheckAllContent = helper?.getView<TextView>(R.id.btCheckAllContent)
                if (item?.content?.length!!>70){
                    helper?.setText(R.id.tvContent,item?.content.substring(0,70))
                    btCheckAllContent?.visibility=View.VISIBLE
                    btCheckAllContent?.setOnClickListener {
                        helper?.setText(R.id.tvContent,item?.content) }
                }else{
                    helper?.setText(R.id.tvContent,item?.content)
                    btCheckAllContent?.visibility=View.GONE
                }
                val btCheckAll = helper?.getView<TextView>(R.id.btCheckAll)
                val thumbLo = helper?.getView<RelativeLayout>(R.id.thumbLo)
                val imgThumb = helper?.getView<ImageView>(R.id.imgThumb)
                val btComment = helper?.getView<ImageView>(R.id.btComment)
                val btZan = helper?.getView<TextView>(R.id.btZan)
                val btShare = helper?.getView<ImageView>(R.id.btShare)
                /*分享*/
                btShare!!.setOnClickListener {
                    val share = TMLinkShare()
                    share.description="${item?.content}"
                    share.title="爆料"
                    share.url="${Contents.PUBLICK_URL}hlhjburst/share/index?bid=${item?.id}"
                    TMShareUtil.getInstance(mContext).shareLink(share)
                }
                /*点赞*/
                if (item?.is_laud==1){
                    val drawable = resources.getDrawable(R.drawable.ic_bl_dianzan1)
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());//对图片进行压缩
                    btZan?.setCompoundDrawables(drawable, null, null, null);
                }else{
                    val drawable = resources.getDrawable(R.drawable.ic_bl_dianzan)
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());//对图片进行压缩
                    btZan?.setCompoundDrawables(drawable, null, null, null);
                }
                btZan?.setOnClickListener {
                    OkGo.get<String>(Contents.PUBLICK_URL+Contents.DIANZAN)
                            .params("token",TMSharedPUtil.getTMToken(mContext))
                            .params("burst_id",item?.id)
                            .execute(object :StringCallback(){
                                override fun onStart(request: Request<String, out Request<Any, Request<*, *>>>?) {
                                    super.onStart(request)
                                    loadDialog.show()
                                }
                                override fun onSuccess(response: Response<String>?) {
                                    loadDialog.dismiss()
                                    val body = response?.body()
                                    val baseBean = Gson().fromJson(body!!, BaseBean::class.java)
                                    if (baseBean.code==1){
                                        if (item?.is_laud==1){
                                            btZan.text = (btZan.text.toString().toInt()-1).toString()
                                            item?.is_laud=0
                                            val drawable = resources.getDrawable(R.drawable.ic_bl_dianzan)
                                            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());//对图片进行压缩
                                            btZan?.setCompoundDrawables(drawable, null, null, null);
                                        }else{
                                            btZan.text = (btZan.text.toString().toInt()+1).toString()
                                            item?.is_laud=1
                                            val drawable = resources.getDrawable(R.drawable.ic_bl_dianzan1)
                                            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());//对图片进行压缩
                                            btZan?.setCompoundDrawables(drawable, null, null, null);
                                        }
                                    }else if (baseBean.code==500){
                                        GoLoginDialog(this@BurstAty).show()
                                    }
                                }
                            })
                }
                /*评论*/
                btComment?.setOnClickListener {
                    /*EditPop(mContext,item?.id.toString(),"0",object :EditPop.CommentSuccessListener{
                        override fun commmentSuccess(str :String) {
                                datas.clear()
                                initData()

                        }
                    }).showAtLocation(father, Gravity.CENTER and  Gravity.BOTTOM,0,0)*/
                }
                /*资源加载*/
                if (item?.source_type==1){
                    thumbLo?.visibility=View.GONE
                    if (item?.source.size>0){
                        nineGridView?.visibility=View.VISIBLE
                    }else{
                        nineGridView?.visibility=View.GONE
                    }
                    val imgs = ArrayList<ImageInfo>()
                    for (i in 0..item?.source!!.size-1){
                        val imageInfo = ImageInfo()
                        imageInfo.thumbnailUrl=Contents.PUBLICK_URL+item?.source[i]
                        imageInfo.bigImageUrl=Contents.PUBLICK_URL+item?.source[i]
                        imgs.add(imageInfo)
                    }
                    nineGridView?.setAdapter(NineGridViewClickAdapter(mContext, imgs))
                }else if (item?.source_type==2){
                    thumbLo?.visibility=View.VISIBLE
                    nineGridView?.visibility=View.GONE
                    thumbLo?.setOnClickListener {
                        val intent = Intent(this@BurstAty,VideoPlayAty::class.java)
                        intent.putExtra("url",item?.source[0])
                        intent.putExtra("img",Contents.PUBLICK_URL+item?.video_thumb)
                        startActivity(intent)
                    }
                    Glide.with(mContext).load(Contents.PUBLICK_URL+item?.video_thumb).into(imgThumb!!)

                }else{
                    nineGridView?.visibility=View.GONE
                    thumbLo?.visibility=View.GONE
                }

                if (item?.comment.size>0){
                    if (item?.comment.size>3){
                        btCheckAll?.visibility=View.VISIBLE
                        val tempDatas=ArrayList<BurstListBean.DataBean.ListBean.CommentBean>()
                        tempDatas.add(0,item?.comment[0])
                        tempDatas.add(0,item?.comment[1])
                        tempDatas.add(0,item?.comment[2])
                        val adp = CommentAdp(mContext,tempDatas)
                        val myListView = helper?.getView<MyListView>(R.id.commentListView)
                        myListView?.adapter=adp
                        myListView?.setOnItemClickListener { parent, view, position, id ->
                            /*EditPop(mContext,item?.id.toString(),tempDatas[position].id.toString(),object :EditPop.CommentSuccessListener{
                                override fun commmentSuccess(str:String) {
                                    initData()
                                }
                            }).showAtLocation(father, Gravity.CENTER and  Gravity.BOTTOM,0,0)*/
                        }
                        btCheckAll?.setOnClickListener {
                            val intent = Intent(mContext, BurstDetailAty::class.java)
                            intent.putExtra("type","1")
                            intent.putExtra("bean",item)
                            intent.putExtra("id",item.id)
//                            intent.putExtra("nickName",item.nickName)
                            intent.putExtra("time",TimeUtils.convertTimeToFormat(item.create_at.toLong()))
                            intent.putExtra("content",item.content)
                            intent.putExtra("icon",item.iconName)
                            startActivity(intent)

                        }
                    }else{
                        btCheckAll?.visibility=View.GONE
                        val adp = CommentAdp(mContext,item?.comment as ArrayList<BurstListBean.DataBean.ListBean.CommentBean>)
                        val myListView = helper?.getView<MyListView>(R.id.commentListView)
                        myListView?.adapter=adp
                        myListView?.setOnItemClickListener { parent, view, position, id ->
                            /*EditPop(mContext,item?.id.toString(),item.comment[position].id.toString(),object :EditPop.CommentSuccessListener{
                                override fun commmentSuccess(str:String) {
                                    initData()
                                }
                            }).showAtLocation(father, Gravity.CENTER and  Gravity.BOTTOM,0,0)*/
                        }
                    }
                }else{
                    btCheckAll?.visibility=View.GONE

                }

            }
        }

        recyclerview.adapter=adp
        recyclerview.layoutManager=LinearLayoutManager(this,LinearLayout.VERTICAL,false)
        adp.addHeaderView(headview)

    }

    private fun initSp() {
        spView.header=DefaultHeader(this)
        spView.footer=DefaultFooter(this)
        spView.setListener(this)
    }

    override fun onLoadmore() {
        page++
        initData()
    }

    override fun onRefresh() {
        page=1
        datas.clear()
        initData()
    }
}
